import axios from 'axios'

const request = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000,
  headers: { 'Content-Type': 'application/json' }
})

// 请求拦截器：每次出站请求自动从localStorage读取token并附加到请求头
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      // 后端使用简单的Authorization头，不需要Bearer前缀
      config.headers.Authorization = token
    }
    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截器：尽量返回业务有效载荷，兼容不同的返回结构
request.interceptors.response.use(
  (response) => {
    const { data } = response
    const ok = data?.code === 0 || data?.success === true || typeof data?.code === 'undefined'
    return ok ? (typeof data?.data !== 'undefined' ? data.data : data) : Promise.reject(new Error(data?.message || data?.msg || '请求失败'))
  },
  (error) => {
    const status = error?.response?.status
    if (status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      if (window.location.pathname !== '/auth') window.location.href = '/auth'
      return Promise.reject(new Error('未授权，请重新登录'))
    }
    return Promise.reject(error)
  }
)

export default request
